import React, { useEffect, useRef, useState } from 'react';
import { Button, DatePicker, Radio } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import * as echarts from 'echarts';
import styles from './HistoryData.module.less';

const HistoryData: React.FC = () => {
  const navigate = useNavigate();
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [viewType, setViewType] = useState<'chart' | 'table'>('chart');

  // 数据
  const xAxisData = ['2023-01', '2023-02', '2023-03', '2023-04', '2023-05', '2023-06', '2023-07'];
  const barData = [45, 58, 65, 35, 52, 48, 22];
  const yearOnYearData = [-25, -22, -18, -20, -15, -18, -25];
  const monthOnMonthData = [-15, -12, -8, -10, -5, -8, -12];

  useEffect(() => {
    // 初始化图表
    if (chartRef.current) {
      chartInstance.current = echarts.init(chartRef.current);
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#1890FF',
              width: 1,
              type: 'dashed'
            }
          },
          backgroundColor: 'rgba(0,0,0,0.65)',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          },
          formatter: function(params: any[]) {
            let result = `<div style="margin-bottom: 4px;">${params[0].axisValue}</div>`;
            params.forEach(param => {
              const value = param.seriesName === '用水量' ? 
                param.value + '万m³' : 
                param.value + '%';
              result += `<div style="display: flex; justify-content: space-between; margin: 4px 0;">
                <span>${param.marker} ${param.seriesName}</span>
                <span style="margin-left: 16px;">${value}</span>
              </div>`;
            });
            return result;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        legend: {
          data: ['用水量', '同比', '环比'],
          left: 'left',
          top: 0,
          itemGap: 24,
          textStyle: {
            color: '#595959'
          }
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: '#E5E5E5'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#595959',
            fontSize: 12
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '万(m³)',
            min: 0,
            max: 80,
            interval: 20,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E5E5'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#595959',
              fontSize: 12
            },
            splitLine: {
              lineStyle: {
                type: 'dashed',
                color: '#E5E5E5',
                opacity: 0.5
              }
            }
          },
          {
            type: 'value',
            name: '百分比(%)',
            min: -40,
            max: 0,
            interval: 10,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#E5E5E5'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#595959',
              fontSize: 12,
              formatter: '{value}%'
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '用水量',
            type: 'bar',
            barWidth: '40%',
            data: barData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(89,126,247,0.03)' },
                { offset: 1, color: 'rgba(89,126,247,0.8)' }
              ]),
              borderRadius: [2, 2, 0, 0]
            }
          },
          {
            name: '同比',
            type: 'line',
            yAxisIndex: 1,
            data: yearOnYearData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#FFA940',
              borderColor: '#FFA940',
              borderWidth: 2
            },
            lineStyle: {
              color: '#FFA940',
              width: 2
            }
          },
          {
            name: '环比',
            type: 'line',
            yAxisIndex: 1,
            data: monthOnMonthData,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            itemStyle: {
              color: '#52C41A',
              borderColor: '#52C41A',
              borderWidth: 2
            },
            lineStyle: {
              color: '#52C41A',
              width: 2
            }
          }
        ],
        markLine: {
          data: [
            {
              xAxis: '2023-03'
            }
          ],
          lineStyle: {
            color: '#1890FF',
            type: 'dashed'
          }
        }
      };

      chartInstance.current.setOption(option);
    }

    // 清理函数
    return () => {
      chartInstance.current?.dispose();
    };
  }, []);

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        
      </div>

      <div className={styles.content}>
        <div className={styles.filterBar}>
          <Radio.Group 
            defaultValue="2" 
            buttonStyle="solid"
            className={styles.timeUnitGroup}
          >
            <Radio.Button value="1">日</Radio.Button>
            <Radio.Button value="2">月</Radio.Button>
            <Radio.Button value="3">年</Radio.Button>
            <Radio.Button value="4" className={styles.timeButton}>
              <span className={styles.timeIcon}>1</span>
              时间
            </Radio.Button>
          </Radio.Group>
          <DatePicker.RangePicker 
            className={styles.rangePicker}
            placeholder={['开始时间', '结束时间']}
          />
          <Button type="primary" className={styles.queryButton}>查询</Button>
          <Button>重置</Button>
          <Button 
          type="link" 
          icon={<LeftOutlined />} 
          onClick={() => navigate('/service/guangai')}
          className={styles.backButton}
          style={{ position: 'absolute', right: '20px' }}
        >
          返回
        </Button>
        </div>

        <div className={styles.chartContainer}>
          <div className={styles.chartHeader}>
            <div className={styles.chartTitle}>
              <span className={styles.dot}></span>
              灌区2022年1月-2023年1月过水量同比环比
            </div>
            <div className={styles.viewButtons}>89
              <Button 
                type={viewType === 'chart' ? 'primary' : 'default'}
                onClick={() => setViewType('chart')}
              >
                图表
              </Button>
              <Button 
                type={viewType === 'table' ? 'primary' : 'default'}
                onClick={() => {
                  setViewType('table');
                  navigate('/service/histable');
                }}
                style={{ marginLeft: 8 }}
              >
                表格
              </Button>
            </div>
          </div>
          <div className={styles.chart} ref={chartRef}></div>
        </div>
      </div>
    </div>
  );
};

export default HistoryData;
